using System;
using System.Text;
using Wikey.Extensibility.Classes;
using Wikey.Transformation.Interfaces;

namespace Wikey.Transformation
{
    public class Transform
    {
        StringBuilder htmlBuilder = new StringBuilder();

        private StringBuilder javaScriptBuilder;
        private IExpressionTransformer ExpressionTransformer;
        readonly TransformationResult FinalTransformation = new TransformationResult();
        
        public Transform()
        {
            htmlBuilder = new StringBuilder();
        }

        private void Evaluate(string content )
        {
             IExpressionEvaluator evaluator =
                new ExpressionEvaluator(Factory.Get<IExpressionParser>() , content)
                    .Run();

            ExpressionTransformer = Factory.Get<IExpressionTransformer>().Set(evaluator.ParsedFunctionQueue);
            ExpressionTransformer.TransformerRepository = new DictionaryTranformerRepository();
            ExpressionTransformer.Do();
        }

        private void DoFinalTransformation()
        {
            foreach (var transformationResult in ExpressionTransformer.Result)
            {
                if (!String.IsNullOrEmpty(transformationResult.Html))
                    htmlBuilder.AppendLine(transformationResult.Html);
                if (!String.IsNullOrEmpty(transformationResult.JavaScript))
                    javaScriptBuilder.AppendLine(transformationResult.JavaScript);

                //javaScriptBuilder.Append("alert('Bahadir is here');");
            }

            FinalTransformation.Html = htmlBuilder.ToString();
            FinalTransformation.JavaScript = javaScriptBuilder.ToString();
        }

        public TransformationResult Do(string content)
        {
            Evaluate(content);

            javaScriptBuilder = new StringBuilder();
            
            DoFinalTransformation();
            

            return FinalTransformation;
        }

        public TransformationResult Do(string content, StringBuilder builder)
        {
            Evaluate(content);
            javaScriptBuilder = builder; 
            DoFinalTransformation();

            return FinalTransformation;
        }

        public static string AsString( string content  )
        {
            return new Transform().Do(content).Html;
        }
    }
}